using IQIGame.Onigao.Game;
using IQIGame.Onigao.GamePlay;
using System.Collections.Generic;

namespace IQIGame.Onigao.Logic
{
    /// <summary>
    /// 开启对话
    /// 参数组1:1：对话cid，2：是否全局对话（全局对话代表所有玩家都会开启）
    /// </summary>
    /// <param name="region"></param>
    /// <param name="triggerServicePlayer"></param>
    public class ExecStartStoryDialog : BaseServiceExecution
    {
        public override void Execute(LevelRegion region, LevelPlayer player)
        {
            var config = _config as ExecParamStartStoryDialog;

            int dialogCid = config.dialogCid;
            bool isGlobal = config.isGlobal;
            int startCid = config.startCid;

            if (!isGlobal && player == null)
            {
                LogicLog.LogError("找不到触发对话的玩家，非全局对话必须通过指定玩家触发。");
                return;
            }

            bool isValid = true;
            List<LevelPlayer> players = ListPool<LevelPlayer>.Get();
            {
                if (!isGlobal)
                {
                    players.Add(player);
                }
                else
                {
                    for (int i = 0; i < region.players.Count; i++)
                    {
                        LevelPlayer p = region.players[i];
                        players.Add(p);
                    }
                }
                for (int i = 0; i < players.Count; i++)
                {
                    LevelPlayer p = players[i];
                    if (p.entity.isOccupied)
                    {
                        LogicLog.LogError("开启对话失败，英雄正被占用。占用状态：" + p.entity.DebugOccupationLog());
                        isValid = false;
                        break;
                    }
                    if (triggerEntity != null)
                    {
                        if (triggerEntity.isOccupied)
                        {
                            LogicLog.LogError("开启对话失败，实体正被占用。占用状态：" + triggerEntity.DebugOccupationLog());
                            isValid = false;
                            break;
                        }
                    }
                }
            }
            ListPool<LevelPlayer>.Put(players);

            if (isValid)
            {
                if (!isGlobal)
                {
                    //设置占用状态
                    player.entity.OccupiedBy(EntityOccupationStatus.Dialog, startCid, triggerEntity);
                    triggerEntity?.OccupiedBy(EntityOccupationStatus.Dialog, startCid, null);
                    //缓存对话总id
                    player.storyDialogCid = dialogCid;
                }

                region.NotifyStartStoryDialog(player, isGlobal, dialogCid, startCid, triggerEntity);
            }
        }
    }
}
